package com.quan.commons.log.utils;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.quan.admin.entity.SysLog;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.commons.core.utils.JwtUtils;
import com.quan.commons.core.utils.SpringContextHolder;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 系统日志工具类
 *
 * @author L.cm
 */
@UtilityClass
public class SysLogUtils {

	public SysLog getSysLog() {
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		SysLog sysLog = new SysLog();
		sysLog.setUsername(Objects.requireNonNull(getUsername(request)));
		sysLog.setRemoteAddr(ServletUtil.getClientIP(request));
		sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
		sysLog.setMethod(request.getMethod());
		sysLog.setUserAgent(request.getHeader("user-agent"));
		sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
		//sysLog.setServiceId(getClientId());
		return sysLog;
	}

	private String getUsername(HttpServletRequest request) {
		final SystemValueProperties properties = SpringContextHolder.getBean(SystemValueProperties.class);
		final String token = request.getHeader("token");
		final String userName = JwtUtils.getUserName(token, properties.getJwt().getSecret());
		return userName;
	}


}
